﻿using System.Collections.Generic;
using EPiServer.Core;

namespace EPiSugar.Navigation
{
    public static class PageReferenceExtensions
    {
        public static PageData Page(this PageReference pageLink)
        {
            return Current.PageSource.GetPage(pageLink);
        }

        public static PageReference ParentLink(this PageReference pageLink)
        {
            return pageLink.Page().ParentLink;
        }

        public static PageData Parent(this PageReference pageLink)
        {
            return pageLink.ParentLink().Page();
        }

        public static PageDataCollection Children(this PageReference parentLink)
        {
            if(parentLink == null) return new PageDataCollection();

            return Current.PageSource.GetChildren(parentLink);
        }

        public static IEnumerable<PageData> Descendants(this PageReference parentLink)
        {
            return parentLink.Descendants(int.MaxValue);
        }

        public static IEnumerable<PageData> Descendants(this PageReference parentLink, int recursionDepth)
        {
            if (parentLink == null)
                yield break;
            if (recursionDepth <= 0)
                yield break;

            foreach (PageData child in parentLink.Children())
            {
                yield return child;
                if(recursionDepth > 1)
                    foreach (PageData grandChild in child.Descendants(recursionDepth - 1))
                        yield return grandChild;
            }
        }

        public static bool HasValue(this PageReference pageLink)
        {
            return !PageReference.IsNullOrEmpty(pageLink);
        }
    }
}